package com.jd.jr.pay.demo.util;

import java.security.MessageDigest;
import org.apache.commons.codec.digest.DigestUtils;

public class MD5Util {
	public static String md5(String data) {
		return DigestUtils.md5Hex(data).toUpperCase();
	}

	public static String md5UpperCase(String text, String salt) throws Exception {
		byte[] bytes = (text + salt).getBytes();

		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(bytes);
		bytes = messageDigest.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xFF) < 16) {
				sb.append("0");
			}
			sb.append(Long.toString(bytes[i] & 0xFF, 16));
		}
		return sb.toString().toUpperCase();
	}

	public static String md5LowerCase(String text, String salt) throws Exception {
		byte[] bytes = (text + salt).getBytes();

		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(bytes);
		bytes = messageDigest.digest();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xFF) < 16) {
				sb.append("0");
			}
			sb.append(Long.toString(bytes[i] & 0xFF, 16));
		}
		return sb.toString().toLowerCase();
	}

	public static boolean verify(String text, String salt, String md5) throws Exception {
		String md5Text = md5UpperCase(text, salt);
		if (md5Text.equalsIgnoreCase(md5)) {
			return true;
		}
		return false;
	}
}
